package cn.acmoj.oj.controller;

import cn.acmoj.oj.bean.Problem;
import cn.acmoj.oj.bean.User;
import cn.acmoj.oj.service.ProblemSetService;
import cn.acmoj.oj.service.SolutionService;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * cn.acmoj.oj.controller
 * Springer
 * 2017-12-23
 */
@Controller
public class ProblemSetController {

    @Resource
    private ProblemSetService problemSetService;
    @Resource
    private SolutionService solutionService;

    @RequestMapping(value = "problemset", method = RequestMethod.GET)
    public String problemSet(@RequestParam(required = false, defaultValue = "1") Integer page,
                             @RequestParam(required = false) Integer pid,
                             @RequestParam(required = false) String search,
                             HttpSession session,
                             HttpServletRequest request) {
        int num = 50;
        if (pid != null) {
            return "redirect:/problem.html?pid=" + pid;
        }
        User user = (User) session.getAttribute("user");
        List<Problem> list;
        int count;
        List<Integer> list_s = new ArrayList<>();
        if (session.getAttribute("privilege") != null) {
            list = problemSetService.getAll(search, page, num);
            count = problemSetService.getAllCount(search);
        } else {
            list = problemSetService.getAllNotAdmin(search, page, num);
            count = problemSetService.getAllNotAdminCount(search);
        }

        //TODO 暂时关闭监测是否AC功能
        if (user != null) {
            list.forEach(problem -> list_s.add(
//                    solutionService.isAccepted(
//                            problem.getProblem_id(),
//                            user.getUser_id()
//                    )
                    0
            ));
        }

        count = count / num + (count % num == 0 ? 0 : 1);

        request.setAttribute("list", list);
        request.setAttribute("list_s", list_s);
        request.setAttribute("count", count);
        return "problemset";
    }
}
